using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.IO.Compression;
using System.Net;
namespace Test {
	class Cache {
		DirectoryInfo dir;
		PLD wc=new PLD();
		public Cache(string key) {
			dir=Directory.CreateDirectory(@"C:\Windows\Temp\"+key+@"\");
		}
		//string path=Environment.GetEnvironmentVariable("tmp");
		public string Get(string source,int timeout) {
      //Console.WriteLine(source);
			string ret="";
			FileInfo fi=new FileInfo(dir.FullName+CalculateMD5Hash(source)+".tmp");


			if(fi.Exists&&fi.LastWriteTime>DateTime.Now.AddMinutes(-timeout))
			{
				ret=UnZipStr(fi.FullName);
			}
			else
			{
				ret=wc.DownloadString(source);
				ZipStr(fi.FullName,ret);
			}

			return ret;
		}
		public class PLD {
			public string DownloadString(string url) {
				WebRequest req=WebRequest.Create(url);
				req.Proxy.Credentials=CredentialCache.DefaultNetworkCredentials;
				WebResponse resp=req.GetResponse();
				using(StreamReader rdr=new StreamReader(resp.GetResponseStream()))
					return rdr.ReadToEnd();
			}

		}

		public string CalculateMD5Hash(string input) {
			// step 1, calculate MD5 hash from input
			MD5 md5=System.Security.Cryptography.MD5.Create();
			byte[] inputBytes=System.Text.Encoding.ASCII.GetBytes(input);
			byte[] hash=md5.ComputeHash(inputBytes);
			// step 2, convert byte array to hex string
			StringBuilder sb=new StringBuilder();
			for(int i=0;i<hash.Length;i++)
				sb.Append(hash[i].ToString("x"));
			return sb.ToString();
		}
		public void ZipStr(string filename,String str) {
			using(FileStream output=new FileStream(filename,FileMode.Create))
			using(DeflateStream gzip=new DeflateStream(output,CompressionMode.Compress))
			using(StreamWriter writer=new StreamWriter(gzip))
				writer.Write(str);
		}
		public string UnZipStr(string filename) {
			using(FileStream inputStream=File.OpenRead(filename))
			using(DeflateStream gzip=new DeflateStream(inputStream,CompressionMode.Decompress))
			using(StreamReader reader=new StreamReader(gzip))
				return reader.ReadToEnd();
		}
	}
}
